<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 目录树 -->
      <el-col
        :lg="4"
        :md="5"
        :sm="6"
        :xs="24"
        class="mb-[12px] !pr-0"
        v-if="showTree"
      >
        <equdevicemodel-tree
          v-model="searchParam.assetTypeId"
          @node-click="search"
          :assetKind="3"
        />
      </el-col>
      <el-col
        :lg="showTree ? 20 : 24"
        :md="showTree ? 19 : 24"
        :sm="showTree ? 18 : 24"
        :xs="24"
      >
        <div class="search-container">
          <el-form :model="searchParam" :inline="true" label-width="63px">
            <!-- <el-form-item label="使用部门">
              <SelectOriganizationDangerGrant
                @change="(ids:string) => getSelectIds(ids, '使用部门')"
                :isCheckStrictly="true"
                :isMultiple="false"
                :disabled="false"
                :data="dataObject('使用部门')"
                :selectData="searchParam.usingDepartmentId"
              />
            </el-form-item> -->

            <el-form-item label="客户">
              <el-select
                v-model="searchParam.projectId"
                placeholder="请选择客户"
                clearable
                filterable
              >
                <el-option
                  v-for="item in customerList"
                  :key="`${item.id}`"
                  :label="`${item.partnerName}`"
                  :value="`${item.id}`"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="产品">
              <el-select
                v-model="searchParam.productId"
                placeholder="请选择产品"
                clearable
                filterable
                :filter-method="productCustomFilter"
              >
                <el-option
                  v-for="item in productFilteredOptions"
                  :key="`${item.id}`"
                  :label="`${item.materialName}`"
                  :value="`${item.id}`"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="工序类型">
              <el-select
                v-model="searchParam.process"
                placeholder="请选择工序类型"
                clearable
                filterable
              >
                <el-option
                  v-for="item in useDictionary('ProcessType')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="模具编号">
              <el-select
                v-model="searchParam.assetCode"
                placeholder="请选择模具编号"
                clearable
                filterable
                :filter-method="mouldCodeCustomFilter"
              >
                <el-option
                  v-for="item in mouldCodeFilteredOptions"
                  :key="`${item.assetCode}`"
                  :label="`${item.assetCode}`"
                  :value="`${item.assetCode}`"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="模具名称">
              <el-input
                clearable
                v-model="searchParam.assetName"
                placeholder="请输入模具名称"
              />
            </el-form-item>
            <el-form-item label="模具选择">
              <el-select
                v-model="searchParam.assetCode"
                placeholder="请选择模具名称"
                clearable
                filterable
                :filter-method="mouldCustomFilter"
              >
                <el-option
                  v-for="item in mouldFilteredOptions"
                  :key="`${item.assetCode}`"
                  :label="`${item.assetName}`"
                  :value="`${item.assetCode}`"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="位置">
              <el-tree-select
                placeholder="请输入位置"
                filterable
                v-model="searchParam.locationId"
                :data="locationInfoTree"
                node-key="id"
                clearable
                :props="{ label: 'locationName', children: 'nodes' }"
                check-strictly
                :render-after-expand="false"
              />
            </el-form-item>
            <el-form-item label="模具状态">
              <el-select
                v-model="searchParam.assetStatus"
                placeholder="请选择模具状态"
                @keyup.enter="search"
                filterable
                clearable
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList('MouldStatus')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="客户资产">
              <el-select
                v-model="searchParam.isCustomer"
                placeholder="是否是客户资产"
                @keyup.enter="search"
                clearable
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList('YesNo')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="reset"><i-ep-refresh />重置</el-button>
              <el-button @click="handelTree" type="primary"
                ><i-ep-location />目录树</el-button
              >

              <!-- <el-button type="primary" @click="toggleSearchArea" link>
                {{ isExpanded ? "收起" : "展开" }}
                <el-icon v-if="isExpanded" class="el-icon--right">
                  <i-ep-arrowUp color="#409EFC" />
                </el-icon>
                <el-icon v-else class="el-icon--right">
                  <i-ep-arrowDown color="#409EFC" />
                </el-icon>
              </el-button> -->
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button type="success" plain @click="openDialog()"
              ><i-ep-plus />新增</el-button
            >
            <el-button type="primary" style="display: none"
              >打印二维码</el-button
            >
            <el-button type="primary" style="display: none">导入</el-button>
            <el-button
              @click="
                useDownload(
                  '/eam/mouldAssetInfo/export',
                  '模具台账',
                  searchParam
                )
              "
            >
              <template #icon><i-ep-download /></template>导出</el-button
            >
            <el-button type="primary" style="display: none"
              >导入模板下载</el-button
            >
            <el-button
              type="danger"
              plain
              :disabled="ids.length === 0"
              @click="handleTableDelete()"
              ><i-ep-delete />删除</el-button
            >
          </template>

          <el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="tableData"
            highlight-current-row
            border
            @selection-change="handleSelectionChange"
            @sort-change="onTableSortChanged"
          >
            <el-table-column type="selection" width="55" align="center" />

            <el-table-column
              sortable
              label="模具编号"
              prop="assetCode"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column
              sortable
              label="模具名称"
              prop="assetName"
              min-width="250"
              show-overflow-tooltip
            />

            <el-table-column
              sortable
              label="客户"
              prop="projectName"
              min-width="120"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.projectName }}
              </template>
            </el-table-column>
            <el-table-column
              sortable
              label="产品"
              prop="productName"
              min-width="180"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.productName }}
              </template>
            </el-table-column>
            <el-table-column
              sortable
              label="工序"
              prop="process"
              min-width="80"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ useDictionary("ProcessType", scope.row.process) }}
              </template>
            </el-table-column>
            <el-table-column
              sortable
              label="模具类型"
              prop="assetTypeCode"
              min-width="120"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ scope.row.assetTypeName }}
              </template>
            </el-table-column>
            <el-table-column
              sortable
              label="库存状态"
              prop="storageStatus"
              min-width="110"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ useDictionary("storageStatus", scope.row.storageStatus) }}
              </template>
            </el-table-column>
            <!-- <el-table-column
              sortable
              label="生产商"
              prop="makerName"
              min-width="110"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ scope.row.makerCode }}{{ scope.row.makerName ? "-" : ""
                }}{{ scope.row.makerName }}
              </template>
            </el-table-column> -->
            <el-table-column
              label="到货日期"
              prop="arrivalDate"
              min-width="180"
              sortable
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{
                  scope.row.arrivalDate
                    ? dayjs(scope.row.arrivalDate).format("YYYY-MM-DD")
                    : ""
                }}
              </template>
            </el-table-column>

            <el-table-column
              sortable
              label="模具位置"
              prop="locationName"
              min-width="120"
              show-overflow-tooltip
            />

            <el-table-column
              sortable
              label="模具状态"
              prop="assetStatus"
              min-width="120"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ useDictionary("MouldStatus", scope.row.assetStatus) }}
              </template>
            </el-table-column>

            <el-table-column
              sortable
              label="启用状态"
              prop="enabled"
              min-width="120"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ useDictionary("YesNo", scope.row.enabled) }}
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              label="操作"
              width="260"
              align="center"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialogdetail(scope.row)"
                  ><i-ep-search />
                  查看
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialog(scope.row)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  link
                  style="display: none"
                  @click="openDialog(scope.row)"
                  ><i-ep-edit />文档</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="deleteItem(scope.row.id)"
                  ><i-ep-delete />删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            :background="true"
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 25, 50, 100]"
            :total="pageable.total"
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-[20px]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>

        <molddeviceinfo-edit
          :visible="addDialog.visible"
          :title="addDialog.title"
          :assetTypeIdTree="assetTypeIdTree"
          :data="addDialog.data"
          @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
          :is-readonly="addDialog.readvisible"
          @change-visible="changeVisible"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { filterOrder } from "@/utils/commonHooks";
import _ from "lodash-es";
import dayjs from "dayjs";
defineOptions({
  name: "EAMMOLDDEVICELEDGER",
  inheritAttrs: false,
});
// 目录树显隐
const showTree = ref(true);
const handelTree = () => {
  showTree.value = !showTree.value;
};
// 切换搜索折叠
const isExpanded = ref(false);
function toggleSearchArea() {
  isExpanded.value = !isExpanded.value;
}
// 请求参数
const requestApi = "/eam/mouldAssetInfo/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
  assetKind: 3,
});

// 初始化搜索参数数据
const searchParamInit = {
  assetName: "",
  assetCode: "",
  assetTypeId: "",
  locationId: "",
  usingDepartmentId: "",
  assetStatus: "",
  manageDepartmentId: "",
  assetManagerId: "",
  repairManagerId: "",
  checkPerson: "",
  arrivalDateSearch: [],
  arrivalDateStart: "",
  arrivalDateEnd: "",
  productId: "",
  projectId: "",
  assetKind: 3,
};

const deleteParam = {
  api: "/eam/mouldAssetInfo/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/mouldAssetInfo/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开模具台账表单弹窗 */
const assetTypeIdTree = ref("");
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改模具台账";
    getInfo(roleObj.id);
  } else {
    assetTypeIdTree.value = searchParam.value.assetTypeId;
    addDialog.title = "新增模具台账";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开模具台账表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "模具台账详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
    assetTypeIdTree.value = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除该条数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/eam/mouldAssetInfo/deleteItem/${id}`,
      method: "post",
    }).then((res) => {
      ElMessage.success("删除成功！");
      search();
    });
  });
}

/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, item: string) {
  if (ids) {
    if (item == "使用部门") {
      searchParam.value.usingDepartmentId = ids;
    } else if (item == "管理部门") {
      searchParam.value.manageDepartmentId = ids;
      personList.value = [];
      changeDept(ids, item);
    } else if (item == "维修部门") {
      searchParam.value.repairDepartmentId = ids;
      personList1.value = [];
      changeDept(ids, item);
    }
  } else {
    if (item == "使用部门") {
      searchParam.value.usingDepartmentId = "";
    } else if (item == "管理部门") {
      searchParam.value.manageDepartmentId = "";
      searchParam.value.assetManagerId = "";
      personList.value = [];
    } else if (item == "维修部门") {
      searchParam.value.repairDepartmentId = "";
      searchParam.value.repairManagerId = "";
      personList1.value = [];
    }
  }
}

// 点击组织机构 选择人员
const personList = ref([]);
const personList1 = ref([]);
const changeDept = async (id, name) => {
  if (id) {
    const res = await request({
      url: "/system/sysUser/getList ",
      method: "post",
      data: {
        departmentId: id,
      },
    });
    if (name == "管理部门") {
      personList.value = res.data;
      // personList.value.map((item: any) => {
      //   item.label = `${item.firstName}`;
      //   item.value = `${item.id}`;
      // });
    }
    if (name == "维修部门") {
      personList1.value = res.data;
      // personList.value.map((item: any) => {
      //   item.label = `${item.firstName}`;
      //   item.value = `${item.id}`;
      // });
    }
  }
};
const dataObject = (item: string) => {
  return {
    name:
      item == "使用部门"
        ? "使用部门"
        : item == "管理部门"
        ? "管理部门"
        : "维修部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};
// 获取制造工厂列表
const makerList: any = ref([]);
const getMakerList = async () => {
  request({
    url: `/eam/eammaker/getList`,
    method: "post",
    data: { assetKind: "3" },
  })
    .then((res) => {
      makerList.value = res.data;
    })
    .catch((res) => {
      console.log(res);
    });
};

// 获取客户
const customerList: any = ref([]);
const getCustomerList = async () => {
  // 获取内容树
  await request({
    url: "/mdm/mdmpartner/getPoList",
    method: "POST",
    data: {},
  }).then((res) => {
    customerList.value = res.data;
  });
};
// 获取项目
const productList: any = ref([]);
const getProductList = async () => {
  // 获取内容树
  await request({
    url: "/mdm/mdmmaterial/getList",
    method: "POST",
    data: { materialType: "3" },
  }).then((res) => {
    productList.value = res.data;
    productFilteredOptions.value = res.data;
  });
};

const productFilteredOptions = ref([]);

// 使用 debounce 包装过滤方法
const productCustomFilter = _.debounce((query: any) => {
  if (!query) {
    productFilteredOptions.value = [...productList.value];
    return;
  }
  productFilteredOptions.value = productList.value.filter((option: any) =>
    option.materialName.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

const mouldList: any = ref([]);
const getMouldList = async () => {
  // 获取内容树
  await request({
    url: "/eam/mouldAssetInfo/getList",
    method: "POST",
    data: {},
  }).then((res) => {
    mouldList.value = res.data;
    mouldFilteredOptions.value = res.data;
    mouldCodeFilteredOptions.value = res.data;
  });
};
const mouldFilteredOptions = ref([]);
const mouldCodeFilteredOptions = ref([]);

// 使用 debounce 包装过滤方法
const mouldCustomFilter = _.debounce((query: any) => {
  if (!query) {
    mouldFilteredOptions.value = [...mouldList.value];
    return;
  }
  mouldFilteredOptions.value = mouldList.value.filter((option: any) =>
    option.assetName.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

// 使用 debounce 包装过滤方法
const mouldCodeCustomFilter = _.debounce((query: any) => {
  if (!query) {
    mouldCodeFilteredOptions.value = [...mouldList.value];
    return;
  }
  mouldCodeFilteredOptions.value = mouldList.value.filter((option: any) =>
    option.assetCode.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

// 处理时间
function getcreateTime(data: any) {
  if (data) {
    searchParam.value.arrivalDateStart = data[0];
    searchParam.value.arrivalDateEnd = data[1];
  } else {
    searchParam.value.arrivalDateStart = "";
    searchParam.value.arrivalDateEnd = "";
  }
}
onMounted(() => {
  getLocationInfoTree();
  getMakerList();
  getProductList();
  getMouldList();
  getCustomerList();
});
</script>

<!-- <style lang="scss" scoped>
:deep(.el-form-item--default .el-form-item__label) {
  // width: 90px !important;
  justify-content: end !important;
  padding: 0 7px 0 0;
}
</style> -->
